package com.iweipan.fragment;

import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;

import com.github.mikephil.charting.charts.CombinedChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.CandleData;
import com.github.mikephil.charting.data.CandleDataSet;
import com.github.mikephil.charting.data.CandleEntry;
import com.github.mikephil.charting.data.CombinedData;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.formatter.IValueFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.listener.ChartTouchListener;
import com.github.mikephil.charting.listener.OnChartGestureListener;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.ViewPortHandler;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.iweipan.R;
import com.iweipan.base.WPBaseFragment;
import com.iweipan.base.WPUrlBase;
import com.iweipan.bean.KlineBean;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import okhttp3.Call;

/**
 * Created by Administrator on 2016/11/17.
 */

public class KLineFragment extends WPBaseFragment {
    @BindView(R.id.chart)
    CombinedChart mChart;
    private String TAG = "KLineFragment";
    private int itemcount;
    private CandleData candleData;
    private CombinedData combinedData;
    private List<CandleEntry> candleEntries = new ArrayList<>();
    private int colorHomeBg;
    private int colorLine;
    private int colorText;
    private ArrayList<String> xVals;
    private int type = 2;
    private OnValueSelected onValueSelected;


    public static KLineFragment newInstance(int type) {

        Bundle args = new Bundle();
        args.putInt("type", type);
        KLineFragment fragment = new KLineFragment();
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public void initData() {
        initChart();
        Bundle arguments = getArguments();
        if (arguments != null) {
            type = (int) arguments.get("type");
        }

        try {
            JSONObject typeJson = new JSONObject();
            typeJson.put("type", type);
            typeJson.put("contract", "XAG1");

            OkHttpUtils.get()
                    .url(WPUrlBase.Get_Now_KLine)
                    .addParams("p", typeJson.toString().intern())
                    .build()
                    .execute(new StringCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {

                        }

                        @Override
                        public void onResponse(String response, int id) {
                            try {

                                JSONObject jsonObject = new JSONObject(response);
                                String code = jsonObject.getString("code");
                                if (code.equals("200")) {
                                    Gson gson = new Gson();
                                    KlineBean klineBean = gson.fromJson(response, KlineBean.class);
                                    if (klineBean.getResult().getDataList() != null && klineBean.getResult().getDataList().size() > 0) {
                                        loadChartData(klineBean.getResult());
                                    }
                                } else if (code.equals("1100")) {

                                }

                            } catch (JSONException e) {

                            } catch (JsonSyntaxException e) {

                            }
//                            Log.d("KLineFragment", response);

                        }
                    });
        } catch (JSONException e) {
            e.printStackTrace();
        }


    }


    public void setOnValueSelected(OnValueSelected onValueSelected) {
        this.onValueSelected = onValueSelected;
    }

    @Override
    public void initDestrory() {

    }

    @Override
    public void initView() {

    }

    @Override
    public View inflaterView(LayoutInflater inflater, ViewGroup container) {
        return inflater.inflate(R.layout.fragment_kline, null);
    }

    private void loadChartData(KlineBean.ResultBean rawData) {
        mChart.resetTracking();
        candleEntries = getCandleEntries(rawData, 0);
        itemcount = candleEntries.size();
        xVals = new ArrayList<>();
        for (int i = 0; i < itemcount; i++) {
            xVals.add(rawData.getDateList().get(itemcount - i - 1));
        }

        combinedData = new CombinedData();

        /*k line*/
        candleData = generateCandleData();
        combinedData.setData(candleData);


        combinedData.setValueFormatter(new IValueFormatter() {
            @Override
            public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
                return xVals.get((int) value % xVals.size());
            }
        });


        mChart.setData(combinedData);//当前屏幕会显示所有的数据
        mChart.animateXY(3000, 300);
        mChart.invalidate();
    }


    public static List<CandleEntry> getCandleEntries(KlineBean.ResultBean rawData, int startIndex) {
        List<CandleEntry> entries = new ArrayList<>();


        for (int i = 0; i < rawData.getDataList().size(); i++) {
            List<String> strings = rawData.getDataList().get(rawData.getDataList().size() - i - 1);
            if (strings == null) {
                Log.e("xxx", "第" + i + "StockBean==null");
                continue;
            }

            CandleEntry entry = new CandleEntry(startIndex + i,
                    Float.parseFloat(strings.get(2)), Float.parseFloat(strings.get(3)),
                    Float.parseFloat(strings.get(0)), Float.parseFloat(strings.get(1)));
            entries.add(entry);
        }

        return entries;
    }

    private CandleData generateCandleData() {


        CandleDataSet set = new CandleDataSet(candleEntries, "");
        set.setAxisDependency(YAxis.AxisDependency.LEFT);
        set.setShadowWidth(0.7f);
        set.setDecreasingColor(Color.rgb(19, 185, 77));
        set.setDecreasingPaintStyle(Paint.Style.FILL);
        set.setIncreasingColor(Color.rgb(245, 67, 55));
        set.setIncreasingPaintStyle(Paint.Style.FILL);
        set.setNeutralColor(Color.rgb(19, 185, 77));
        set.setShadowColorSameAsCandle(true);
        set.setHighlightLineWidth(1f);
        set.setHighLightColor(Color.BLUE);
        set.setDrawValues(false);


        CandleData candleData = new CandleData();

        candleData.addDataSet(set);

        return candleData;
    }


    private void initChart() {
        colorHomeBg = Color.WHITE;
        colorLine = getResources().getColor(R.color.pay_text_color);
        colorText = getResources().getColor(R.color.pay_text_color);
        Description description = new Description();
        description.setText("");
        mChart.setDescription(description);

        mChart.setDrawGridBackground(true);
        mChart.setBackgroundColor(colorHomeBg);
        mChart.setGridBackgroundColor(colorHomeBg);
        mChart.setScaleYEnabled(false);
        mChart.setPinchZoom(true);
        mChart.setDrawValueAboveBar(false);
        mChart.setNoDataText("加载中...");
        mChart.setAutoScaleMinMaxEnabled(true);
        mChart.setDragEnabled(true);
        mChart.setDrawOrder(new CombinedChart.DrawOrder[]{CombinedChart.DrawOrder.CANDLE, CombinedChart.DrawOrder.LINE});


        XAxis xAxis = mChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setDrawGridLines(true);
        xAxis.setGridColor(colorLine);
        xAxis.setTextColor(colorText);
        xAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {

                return xVals.get((int) value % xVals.size());
            }

        });

        YAxis leftAxis = mChart.getAxisLeft();
        leftAxis.setLabelCount(4, false);
        leftAxis.setDrawGridLines(true);
        leftAxis.setDrawAxisLine(true);
        leftAxis.setGridColor(colorLine);
        leftAxis.setTextColor(colorText);

        YAxis rightAxis = mChart.getAxisRight();
        rightAxis.setEnabled(false);

        Legend legend = mChart.getLegend();
        legend.setEnabled(false);
        mChart.setOnChartGestureListener(new OnChartGestureListener() {
            @Override
            public void onChartGestureStart(MotionEvent me, ChartTouchListener.ChartGesture lastPerformedGesture) {
                onValueSelected.onTouch(false);
            }

            @Override
            public void onChartGestureEnd(MotionEvent me, ChartTouchListener.ChartGesture lastPerformedGesture) {
                onValueSelected.onTouch(true);
            }

            @Override
            public void onChartLongPressed(MotionEvent me) {

            }

            @Override
            public void onChartDoubleTapped(MotionEvent me) {

            }

            @Override
            public void onChartSingleTapped(MotionEvent me) {

            }

            @Override
            public void onChartFling(MotionEvent me1, MotionEvent me2, float velocityX, float velocityY) {

            }

            @Override
            public void onChartScale(MotionEvent me, float scaleX, float scaleY) {

            }

            @Override
            public void onChartTranslate(MotionEvent me, float dX, float dY) {

            }
        });

        mChart.setOnChartValueSelectedListener(new OnChartValueSelectedListener() {


            @Override
            public void onValueSelected(Entry e, Highlight h) {
                CandleEntry candleEntry = (CandleEntry) e;
                float change = (candleEntry.getClose() - candleEntry.getOpen()) / candleEntry.getOpen();
                NumberFormat nf = NumberFormat.getPercentInstance();
                nf.setMaximumFractionDigits(2);
                String changePercentage = nf.format(Double.valueOf(String.valueOf(change)));
                Log.d("qqq", "最高" + candleEntry.getHigh() + " 最低" + candleEntry.getLow() +
                        " 开盘" + candleEntry.getOpen() + " 收盘" + candleEntry.getClose() +
                        " 涨跌幅" + changePercentage);
                float[] strings = {candleEntry.getHigh(),
                        candleEntry.getLow(),
                        candleEntry.getOpen(), candleEntry.getClose()};
                if (onValueSelected != null) {
                    onValueSelected.setOnValueSelected(strings);
                }
            }

            @Override
            public void onNothingSelected() {

            }
        });
    }

    public interface OnValueSelected {
        void setOnValueSelected(float[] strings);

        void onTouch(boolean isEnd);
    }

}
